import { CSSRuleObject, styled } from "styledfc";
import Main from "@/components/Main";
import img from "./img";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { UserInfo } from "../User";
import { Dialog, Toast } from "react-vant";
import { useSelector } from "react-redux";
import { PositionCss } from "@/utils/styledfc";
import { changeAvatarById } from "@/api";
interface ControlItemType {
    text: string;
    imgUrl: string;
    pathUrl: string;
}
export default function index() {
    const navigate = useNavigate();
    const [controlList, setcontrolList] = useState<ControlItemType[]>([
        { text: "修改信息", imgUrl: img.messageIcon, pathUrl: "/info" },
        { text: "收藏记录", imgUrl: img.collectIcon, pathUrl: "/col" },
        { text: "浏览记录", imgUrl: img.browseIcon, pathUrl: "/list/browse/1" },
        { text: "退出登录", imgUrl: img.editIcon, pathUrl: "/edit" },
    ]);
    const userLocal = localStorage.getItem("pet-userInfo");
    useEffect(() => {
        if (!userLocal) {
            setcontrolList(() => controlList.filter((v) => v.text !== "退出登录"));
        }
    }, [userLocal]);
    const [userInfo, setUserInfo] = useState<Partial<UserInfo> | null>(!!userLocal && JSON.parse(userLocal as string));
    const handleClick = (item: ControlItemType) => {
        if (!userInfo) {
            Toast("请先登录");
            return;
        }
        if (item.pathUrl === "/edit") {
            Dialog.confirm({
                message: "确认退出登录?",
                confirmButtonColor: "#ee0a24",
                onConfirm: () => {
                    setUserInfo(null);
                    localStorage.removeItem("pet-userInfo");
                    setcontrolList(() => controlList.filter((v) => v.text !== "退出登录"));
                },
            });
            return;
        }
        item.pathUrl && navigate(item.pathUrl);
    };
    const handleLogin = () => {
        // setcontrolList([...controlList, { text: "退出登录", imgUrl: img.editIcon, pathUrl: "/edit" }]);
        navigate("/user/login");
    };
    const { config } = useSelector((state: any) => state.oss);
    const changeAvatar = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;
        const formData = new FormData();
        // u 用户
        const u = JSON.parse(userLocal as string);
        // t 上传的文件名
        const t = u.acc + "-" + new Date().getTime() + "." + file.name.split(".")[file.name.split(".").length - 1];
        formData.append("key", t);
        formData.append("policy", config.policy);
        formData.append("OSSAccessKeyId", config.OSSAccessKeyId);
        formData.append("success_action_status", "200");
        formData.append("signature", config.signature);
        formData.append("file", file);
        await changeAvatarById(config.host, formData, t, u.id);
        localStorage.setItem("pet-userInfo", JSON.stringify({ ...userInfo, img: config.host + "/" + t }));
        setUserInfo(() => ({ ...userInfo, img: config.host + "/" + t }));
    };
    return (
        <div className={indexStyle.className}>
            <div className="index__header">
                <div className="index__header_img">
                    {userInfo ? (
                        <>
                            <img src={userInfo.img?.includes("http") ? userInfo.img : "http://localhost:3001" + userInfo.img} />
                            <input type="file" className="file" onChange={changeAvatar} />
                        </>
                    ) : (
                        <span onClick={handleLogin} className="loginGo">
                            +
                        </span>
                    )}
                </div>
                <div className="index__header_name">{userInfo?.nick_name ?? ""}</div>
            </div>
            <Main>
                <div className="index__control">
                    {controlList.map((item) => (
                        <div className="index__control-tab" key={item.text} onClick={() => handleClick(item)}>
                            <img src={item.imgUrl} />
                            <span>{item.text}</span>
                        </div>
                    ))}
                </div>
            </Main>
        </div>
    );
}
const indexStyle = styled({
    fontSize: "16rem",
    backgroundColor: "#a1b275",
    ".index__header": {
        height: "118rem",
        paddingTop: "30rem",
        width: "100%",
        ".loginGo": {
            display: "block",
            fontSize: "36rem",
            color: "#a1b275",
            textAlign: "center",
            lineHeight: "70rem",
            backgroundColor: "#f3f2f2",
            width: "100%",
            height: "100%",
        },
        ".index__header_img": {
            height: "80rem",
            width: "80rem",
            backgroundColor: "white",
            margin: "0 auto",
            borderRadius: "15rem",
            border: "2rem solid white",
            boxSizing: "border-box",
            marginBottom: "4rem",
            overflow: "hidden",
            position: "relative",
            ">img": {
                width: "100%",
                height: "100%",
                objectFit: "cover",
            },
            ".file": {
                opacity: "0",
                width: "100%",
                height: "100%",
                ...(PositionCss("absolute", { top: "0", left: "0" }) as CSSRuleObject),
            },
        },

        ".index__header_name": {
            margin: "8rem auto 0",
            textAlign: "center",
            color: "rgba(255, 255, 255, 0.86)",
            fontSize: "18rem",
        },
    },
    ".index__control": {
        transform: "translateY(30rem)",
        width: " 344rem",
        margin: " 0 auto",
        height: "calc( 100vh - 250rem)",

        ".index__control-tab": {
            display: "flex",
            color: "#3f4f3a",
            padding: "10rem 10rem",
            lineHeight: "30rem",
            alignItems: "center",
            ">img": {
                height: "30rem",
                width: "30rem",
            },
            ">span": {
                marginLeft: "10rem",
            },
        },
    },
});
